<template>
  <div class="material-img">
    <el-card shadow="never" class="selectCard">
      <el-form label-position="right" label-width="6rem">
        <el-row>
          <el-col :span="8">
            <el-form-item label="图片名称：">
              <el-input v-model="searchParams.name" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="排序规则：">
              <el-select v-model="searchParams.rule" @change="getMaterialList(1)">
                <el-option :value="1" label="按更新时间" />
                <el-option :value="2" label="按上传时间" />
                <el-option :value="3" label="按名称顺序" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" style="float: right;align-items: center;justify-content: center;">
            <SearchButton :default-params="searchParams" @refreshParams="refreshParams" @getList="getList1" />
          </el-col>
        </el-row>

      </el-form>
    </el-card>
    <div class="content">
      <div class="left">
        <el-card shadow="never">
          <el-checkbox v-model="checkAll" class="mr10" @change="changeAll">全选</el-checkbox>
          <el-button type="primary" size="small" @click="openAddDialog">添加</el-button>
          <el-button size="small" @click="delAll">批量删除</el-button>
          <el-button size="small" @click="openMoveDialog('')">批量移动</el-button>
          <ul class="imgs">
            <li v-for="(item, index) in list" :key="index">
              <div class="img">
                <img :src="item.path" alt="">
              </div>
              <div class="item flex-b lh30" style="width: 100px">
                <div class="overflow1 " :title="item.name">
                  {{ item.name }}
                </div>
                <el-checkbox v-model="item.ischeck" class="grey mr0" @change="changeOne(item)" />
              </div>
              <div class="item flex-b grey" style="width: 100px">
                <i class="el-icon-edit-outline" @click="openMoveDialog(item.id)" />
                <el-button type="text" size="small" class="copy-btn" :data-clipboard-text="item.path" @click="copyUrl">链接</el-button>
                <i class="el-icon-delete" @click="delOne(item.id)" />
              </div>
            </li>
          </ul>
          <vxe-pager
            :current-page.sync="searchParams.pageNum"
            :page-size.sync="searchParams.pageSize"
            :total="total"
            :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total']"
            @page-change="getMaterialList"
          />
        </el-card>
      </div>
      <div class="right">
        <el-card shadow="never" class="mb10">
          <div class="flex-b mb10 fz14">
            <div>
              图片分组
            </div>
          </div>
          <el-input v-model="groupName" class="search-btn" placeholder="分组名称">
            <template slot="append">
              <el-button @click="getMaterialGroupList">搜索</el-button>
            </template>
          </el-input>
          <el-tree class="fz14" :data="treeList" :highlight-current="true" :expand-on-click-node="false" default-expand-all @node-click="handleNodeClick">
            <span slot-scope="{ data }" class="custom-tree-node">
              <span>{{ data.name }} ({{ data.sourceCount }})</span>
            </span>
          </el-tree>
        </el-card>
        <el-card shadow="never">
          <div class="flex-b font-size12 pointer">
            <el-button size="small" @click="openGroupDialog">添加分组</el-button>
            <el-button size="small" @click="openRenameDialog">修改分组</el-button>
            <el-popover v-model="delPopver" placement="top" width="400">
              <p>确定删除所选分组吗？</p>
              <p>组内全部图片将自动归入未分组。</p>
              <div style="text-align: right; margin: 0">
                <el-button size="mini" type="text" @click="delPopver = false">取消</el-button>
                <el-button type="primary" size="mini" @click="delMaterialGroup">确定</el-button>
              </div>
              <el-button slot="reference" size="small">删除分组</el-button>
            </el-popover>
          </div>
        </el-card>
      </div>
    </div>
    <el-dialog v-if="groupDialog" width="30%" :title="groupTitle" :visible.sync="groupDialog" :close-on-click-modal="false">
      <el-form ref="groupForm" :model="groupParams" :rules="groupRules" label-width="7rem">
        <el-row>
          <el-col :span="23">
            <el-form-item prop="name" label="分组名称：">
              <el-input v-model="groupParams.name" />
            </el-form-item>
          </el-col>
          <el-col :span="23">
            <el-form-item prop="sort" label="排序：" class="flex-just">
              <div class="flex1">
                <el-input-number v-model="groupParams.sort" :precision="0" :controls="false" />
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="groupDialog = false">取 消</el-button>
        <el-button type="primary" @click="clickSureGroup">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog v-if="addDialog" width="40%" title="添加" :visible.sync="addDialog" :close-on-click-modal="false">
      <el-form ref="addForm" :model="addParams" :rules="addRules" label-width="7rem">
        <el-row>
          <el-col :span="23">
            <el-form-item prop="parentId" label="所在分组：">
              <el-select v-model="addParams.parentId" filterable placeholder="请选择">
                <el-option v-for="item in selectList" :key="item.index" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="23">
            <el-form-item prop="sources" label="选择图片：">
              <UploadCop ref="meterial" :max-size="2" :multiple="true" :limit="99999" :file-list="fileList" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialog = false">取 消</el-button>
        <el-button type="primary" @click="clickSureAdd">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog v-if="renameDialog" width="30%" title="修改" :visible.sync="renameDialog" :close-on-click-modal="false">
      <el-form ref="renameForm" :model="renameParams" :rules="renameRules" label-width="7rem">
        <el-row>
          <el-col :span="23">
            <el-form-item prop="name" label="分组名称：">
              <el-input v-model="renameParams.name" />
            </el-form-item>
          </el-col>
          <el-col :span="23">
            <el-form-item prop="sort" label="排序：" class="flex-just">
              <div class="flex1">
                <el-input-number v-model="renameParams.sort" :precision="0" :controls="false" />
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="renameDialog = false">取 消</el-button>
        <el-button type="primary" @click="clickSureRename">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog v-if="moveDialog" :title="dialogTitle" :visible.sync="moveDialog" :close-on-click-modal="false">
      <el-form ref="moveForm" :model="moveParams" :rules="moveRules" label-width="7rem">
        <el-row>
          <el-col :span="12">
            <el-form-item prop="parentId" label="移动分组：">
              <el-select v-model="moveParams.parentId" filterable placeholder="请选择">
                <el-option v-for="item in selectList" :key="item.value" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-if="dialogType == 0" :span="12">
            <el-form-item prop="name" label="图片名称：">
              <el-input v-model="moveParams.name" />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row v-if="dialogType == 0">
          <el-col :span="12">
            <el-form-item prop="parentId" label="图片名称">
              <el-input v-model="moveParams.name" />
            </el-form-item>
          </el-col>
        </el-row> -->
        <el-row>
          <el-col v-if="dialogType == 0" :span="24">
            <el-form-item label="图片路径：">
              <el-input v-model="imagePath" disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="moveDialog = false">取 消</el-button>
        <el-button type="primary" @click="clickSureMove">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Clipboard from 'clipboard'
import SearchButton from '@/components/SearchButton'
import { getMaterialGroupList, addMaterialGroup, renameGroup, delMaterialGroup, addMaterial, getMaterialList, delMaterial, moveGroup, getThisImgInfo, modifyThisImgInfo } from '@/api/cop/source'
import UploadCop from '@/components/upload/uploadCop'

export default {
  components: {
    SearchButton,
    UploadCop
  },
  data() {
    return {
      imageID: '',
      imageParentId: '',
      imageName: '默认',
      imagePath: '',
      // 0 为修改信息 1为移动
      dialogType: 1,
      // 后缀
      afterPic: '',
      clipboardText: '',
      dialogTitle: '移动分组',
      checkAll: false,
      moveDialog: false,
      moveParams: {
        parentId: '',
        name: '',
        id: '',
        ids: []
      },
      moveRules: {
        parentId: [{ required: true, message: '请选择分组', trigger: 'change' }],
        name: [{ required: true, message: '请输入图片名称', trigger: 'blur' }]
      },
      tagList: [{ name: '不限', value: '' }, { name: 'bmp', value: 'bmp' }, { name: 'png', value: 'png' }, { name: 'jpeg', value: 'jpeg' }, { name: 'jpg', value: 'jpg' }, { name: 'gif', value: 'gif' }],
      groupName: '',
      searchParams: {
        parentId: '',
        type: 1,
        rule: 1,
        name: '',
        contentType: '',
        pageNum: 1,
        pageSize: 20
      },
      total: 1,
      list: [],
      delPopver: false,
      renameDialog: false,
      renameParams: {
        name: ''
      },
      renameRules: {
        name: [{ required: true, message: '请输入分组名称', trigger: 'blur' }],
        sort: [{ required: true, message: '请输入排序', trigger: 'blur' }]
      },
      fileList: [],
      treeList: [],
      selectList: [],
      checked: false,
      name: '',
      groupDialog: false,
      groupParams: {
        type: 1
      },
      groupRules: {
        name: [{ required: true, message: '请输入分组名称', trigger: 'blur' }],
        sort: [{ required: true, message: '请输入排序', trigger: 'blur' }]
      },
      groupTitle: '',

      addDialog: false,
      addParams: {
        type: 1,
        parentId: '',
        sources: []
      },
      addRules: {
        parentId: [{ required: true, message: '请选择分组', trigger: 'change' }],
        sources: [{ type: 'array', required: true, message: '请选择图片', trigger: 'change' }],
        name: [{ required: true, message: '请输入分组名称', trigger: 'blur' }]
      }
    }
  },
  mounted() {
    this.getMaterialGroupList()
  },
  methods: {
    // 复制图片路径
    copyUrl() {
      const _this = this
      const clipboard = new Clipboard('.copy-btn') // 这里括号里填写上面点击事件绑定的class名
      clipboard.on('success', e => {
        // 复制成功，提示根据自己项目实际使用的UI来写
        _this.$message.success('复制图片链接成功')
        // 释放内存
        clipboard.destroy()
      })
      clipboard.on('error', e => {
        // 不支持复制，提示根据自己项目实际使用的UI来写
        _this.$message.error('该浏览器不支持自动复制')
        // 释放内存
        clipboard.destroy()
      })
    },
    refreshParams(params) {
      this.groupName = ''
      this.searchParams = params
      this.getMaterialGroupList(1)
    },
    getList1() {
      this.getMaterialGroupList()
    },
    openMoveDialog(id) {
      if (id === '') {
        this.dialogType = 1
        this.dialogTitle = '移动分组'
        const arr = this.list.filter(item => item.ischeck).map(item => item.id)
        if (arr.length === 0) {
          this.$message.error('请选择图片')
          return false
        } else {
          this.moveParams.ids = arr
          this.moveDialog = true
        }
      } else if (id !== '') {
        this.dialogType = 0
        this.moveParams.ids = [id]
        this.dialogTitle = '编辑图片信息'
        const imgId = id
        this.moveParams.id = id

        console.log('imgId', imgId)
        getThisImgInfo({ id: imgId }).then(res => {
          // if(res.code == 10000){
          this.moveParams.name = res.name
          this.afterPic = res.name.split('.')[1]
          this.imagePath = res.path
          this.clipboardText = res.path
          this.moveParams.parentId = res.parentId
          this.moveParams.parentId = res.parentId
          this.moveDialog = true
          console.log('res', res.parentId)
        })
      }
      this.moveParams.parentId = ''
    },
    clickSureMove() {
      if (this.dialogType === 0) {
        this.$refs.moveForm.validate((valid) => {
          if (valid) {
            console.log('this.moveParams', this.moveParams)
            modifyThisImgInfo(this.moveParams).then(res => {
              this.$message.success('修改成功！')
              this.getMaterialGroupList(1)
              this.moveDialog = false
              console.log('res', res)
            })
          }
        })
      } else {
        this.$refs.moveForm.validate((valid) => {
          if (valid) {
            moveGroup(this.moveParams).then(res => {
              this.$message.success('移动成功！')
              this.getMaterialGroupList(1)
              this.moveDialog = false
            })
          }
        })
      }
    },
    delAll() {
      this.moveParams.ids = this.list.filter(item => item.ischeck).map(item => item.id)
      this.del()
    },
    delOne(id) {
      this.moveParams.ids = [id]
      this.del()
    },
    del() {
      this.$confirm('此操作将永久删除数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delMaterial({ ids: this.moveParams.ids }).then(res => {
          this.$message.success('删除成功！')
          this.getMaterialGroupList(1)
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    changeAll(val) {
      this.list.forEach(item => {
        item.ischeck = this.checkAll
      })
    },
    changeOne(value) {
      this.checkAll = this.list.length === this.list.filter(item => item.ischeck).length
    },
    getMaterialList(type) {
      if (type === 1) {
        this.searchParams.pageNum = 1
      }
      getMaterialList({ ...this.searchParams }).then(res => {
        this.checkAll = false
        res.records.forEach(item => {
          item.ischeck = false
        })
        this.total = res.total
        this.list = res.records
      })
    },
    getMaterialGroupList(type = 0) {
      getMaterialGroupList({ type: 1, name: this.groupName }).then(res => {
        this.treeList = res
        this.selectList = res[0].children
        if (res.length !== 0) {
          this.searchParams.parentId = ''
          if (type === 1) {
            this.searchParams.pageNum = 1
          }
          this.getMaterialList()
        }
      })
    },
    openGroupDialog() {
      this.groupTitle = '添加'
      this.groupParams = {
        type: 1
      }
      this.groupDialog = true
    },
    clickSureGroup() {
      this.$refs.groupForm.validate((valid) => {
        if (valid) {
          this.groupParams.parentId = this.treeList[0].id
          addMaterialGroup(this.groupParams).then(res => {
            this.getMaterialGroupList(1)
            this.$message.success('添加成功！')
            this.groupDialog = false
          })
        }
      })
    },
    openAddDialog() {
      this.addParams.parentId = ''
      this.addParams.sources = []
      this.addDialog = true
    },
    clickSureAdd() {
      alert(JSON.stringify(this.$refs.meterial.key))
      this.addParams.sources = this.$refs.meterial.key.map(item => {
        return {
          name: item.url,
          path: item.name,
          contentType: item.url.split('.')[1]
        }
      })
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          addMaterial(this.addParams).then(res => {
            this.$message.success('添加成功！')
            this.addDialog = false
            this.getMaterialGroupList(1)
          })
        }
      })
    },
    handleNodeClick(data) {
      this.renameParams.id = data.name === '全部' ? '' : data.id
      this.renameParams.sort = data.sort
      this.renameParams.name = data.name
      this.searchParams.parentId = data.name === '全部' ? '' : data.id
      this.getMaterialList(1)
    },
    delMaterialGroup() {
      if (this.renameParams.id === undefined) {
        this.$message.error('请先选择分组')
        this.delPopver = false
        return false
      }
      if (this.renameParams.name === '全部' || this.renameParams.name === '未分组') {
        this.$message.error('此分组不允许删除！')
        this.delPopver = false
        return false
      }
      delMaterialGroup({ id: this.renameParams.id }).then(res => {
        this.getMaterialGroupList(1)
        this.$message.success('删除成功！')
        this.delPopver = false
      })
    },
    openRenameDialog() {
      if (this.renameParams.id === undefined) {
        this.$message.error('请先选择分组')
        return false
      }
      if (this.renameParams.name === '全部' || this.renameParams.name === '未分组') {
        this.$message.error('此分组不允许修改')
        return false
      }
      this.renameDialog = true
    },
    clickSureRename() {
      if (this.renameParams.name === '全部' || this.renameParams.name === '未分组') {
        this.$message.error('此分组不允许修改！')
        return false
      }
      this.$refs.renameForm.validate((valid) => {
        if (valid) {
          renameGroup(this.renameParams).then(res => {
            this.getMaterialGroupList(1)
            this.renameDialog = false
            this.$message.success('修改成功！')
          })
        }
      })
    }
  }
}
</script>

<style lang="scss">
.material-img {
  .copy-btn{
    padding: 0 !important;
  }
  .imgs {
    display: flex;
    flex-wrap: wrap;
    padding-top: 10px;
    li {
      width: 19%;
      margin-right: 1.25%;
      margin-bottom: 10px;
      display: flex;
      justify-content: space-around;
      align-items: center;
      flex-direction: column;
      .img {
        width: 100px;
        padding-top: 100px;
        position: relative;
        img {
          position: absolute;
          height: 100%;
          width: 100%;
          top: 0;
          left: 0;
        }
      }
    }
    li:nth-child(5n) {
      margin-right: 0;
    }
  }
  .el-tree {
    max-height: 620px;
    max-width: 100%;
  }
  .el-tree>.el-tree-node {
    display: inline-block;
    width: 100%;
    max-height: 650px;
  }
}
</style>
